package log

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sync"
	"time"
)

/**负责写文件*/

type Writer struct {
	path      string
	fileName  string
	file      *os.File
	msgs      chan string
	waitQueue *sync.WaitGroup
}

func NewWriter(path string, fileName string) (*Writer, error) {
	writer := &Writer{
		path:      path,
		fileName:  fileName,
		msgs:      make(chan string, 3),
		waitQueue: new(sync.WaitGroup),
	}
	writer.file = writer.NewFile()

	go writer.consume()
	return writer, nil

}

func (this *Writer) NewFile() *os.File {
	filePath := filepath.Join(this.path, this.fileName)
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		if file != nil {
			file.Close()
		}
		panic("日志文件打开失败")
	}
	return file
}

//把内容写入文件
func (this *Writer) write(msg string) error {
	_, err := this.file.WriteString(msg)
	if err != nil {
		log.Fatal("write file erro %S", err)
	}
	log.Println(msg)
	return err
}

func (this *Writer) PutMsg(msg string) {
	if msg == "" {
		return
	}
	this.msgs <- msg
	this.waitQueue.Add(1)
}

//消费msg里面的消息，写入文件
func (this *Writer) consume() {
	for {
		select {
		case msg, ok := <-this.msgs:
			if msg != "" && ok {
				this.write(msg)
				this.waitQueue.Done()
				time.Sleep(1 * time.Second)
			} else {
				fmt.Println("consume error")
			}
		}
	}
}

func (this *Writer) Close() {
	this.waitQueue.Wait() //等待所有消息消费完
	this.file.Close()
}
